<!-- 来料检验单列表 -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="来料检验单编号" prop="iqcCode">
        <el-input
          v-model="queryParams.iqcCode"
          placeholder="请输入来料检验单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源单据编号" prop="sourceDocCode">
        <el-input
          v-model="queryParams.sourceDocCode"
          placeholder="请输入来源单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商批次号" prop="supplierBatch">
        <el-input
          v-model="queryParams.supplierBatch"
          placeholder="请输入供应商批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货物名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入货物名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="stockSfn">
        <el-input
          v-model="queryParams.stockSfn"
          placeholder="请输入规格型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检测结果" prop="checkResult">
        <el-select
          v-model="queryParams.checkResult"
          placeholder="请选择检测结果"
          clearable
          style="width: 100%"
        >
          <el-option v-for="item in checkResultOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单据状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择单据状态"
          clearable
          style="width: 100%"
        >
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="检测日期" prop="inspectDate">
        <el-date-picker clearable
          v-model="queryParams.inspectDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择检测日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ldzl-qc:iqc:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ldzl-qc:iqc:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ldzl-qc:iqc:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ldzl-qc:iqc:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="iqcList"
      @selection-change="handleSelectionChange"
      border
      size="mini"
      style="width: 100%"
      :row-style="getRowStyle"
      :cell-style="{padding: '0px'}"
      :header-cell-style="{height: '40px', padding: '0px'}"
    >
      <el-table-column type="selection" width="45" align="center" fixed="left" />

      <el-table-column label="检验单编号" align="center" prop="iqcCode" width="120" :show-overflow-tooltip="true" fixed="left">
        <template slot-scope="scope">
          <span
            class="clickable-code"
            @click="goToDetail(scope.row)"
            :title="'点击查看详情'"
          >
            {{ scope.row.iqcCode }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="检验单名称" align="center" prop="iqcName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="来源单据类型" align="center" prop="sourceDocType" width="100">
        <template slot-scope="scope">
          <el-tag :type="getSourceDocTypeTagType(scope.row.sourceDocType)" size="mini">
            <span v-if="scope.row.sourceDocType === 1 || scope.row.sourceDocType === '1'">出货检验单</span>
            <span v-else-if="scope.row.sourceDocType === 2 || scope.row.sourceDocType === '2'">来料货检验单</span>
            <span v-else-if="scope.row.sourceDocType === 3 || scope.row.sourceDocType === '3'">过程检验单</span>
            <span v-else-if="scope.row.sourceDocType === 4 || scope.row.sourceDocType === '4'">退料检验单</span>
            <span v-else>{{ scope.row.sourceDocType }}</span>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="供应商名称" align="center" prop="supplierName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="货物名称" align="center" prop="goodsName" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="规格型号" align="center" prop="stockSfn" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="单位" align="center" prop="unitName" width="60" />
      <el-table-column label="接收数量" align="center" prop="quantityRecivedNum" width="80" />
      <el-table-column label="检测数量" align="center" prop="quantityCheckNum" width="80" />
      <el-table-column label="检测结果" align="center" prop="checkResult" width="80">
        <template slot-scope="scope">
          <el-tag :type="getCheckResultTagType(scope.row.checkResult)" size="mini">
            {{ formatCheckResult(scope.row.checkResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="来料日期" align="center" prop="reciveDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reciveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检测日期" align="center" prop="inspectDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)" size="mini">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click.stop="goToDetail(scope.row)"
            v-hasPermi="['ldzl-qc:iqc:view']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click.stop="handleUpdate(scope.row)"
            v-hasPermi="['ldzl-qc:iqc:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click.stop="handleDelete(scope.row)"
            v-hasPermi="['ldzl-qc:iqc:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-warning"
            @click.stop="handleDefectRecord(scope.row)"
            v-hasPermi="['ldzl-qc:iqc:defect']"
          >缺陷记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改ldzl-qc对话框 -->
    <iqc-dialog
      :visible.sync="open"
      :title="title"
      :iqcData="form"
      @success="handleDialogSuccess"
      @cancel="handleDialogCancel"
    />

    <!-- 缺陷记录对话框 -->
    <defect-record-dialog
      :visible.sync="defectOpen"
      :title="'缺陷记录 - ' + defectTitle"
      :qcId="defectIqcId"
      :qcType="'1'"
      :lineId="null"
    />
  </div>
</template>

<script>
import { listIqc, getIqc, delIqc } from "@/api/qc/IncomingInspection"
import IqcDialog from "./IqcDialog";
import DefectRecordDialog from "@/views/qc/components/DefectRecordDialog";

export default {
  name: "Iqc",
  components: {
    IqcDialog,
    DefectRecordDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // ldzl-qc表格数据
      iqcList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 缺陷记录对话框
      defectOpen: false,
      defectTitle: "",
      defectIqcId: null,

      // 检测结果选项
      checkResultOptions: [
        { value: "1", label: "合格" },
        { value: "2", label: "不合格" },
        { value: "3", label: "待检" }
      ],
      // 单据状态选项
      statusOptions: [
        { value: "1", label: "草稿" },
        { value: "2", label: "已提交" },
        { value: "3", label: "已审核" }
      ],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        iqcCode: null,
        iqcName: null,
        sourceDocCode: null,
        goodsName: null,
        stockSfn: null,
        status: null,
        beginTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 待检高亮ID
      highlightId: null
    }
  },
  created() {
    // 检查路由参数，获取检验单编号
    if (this.$route.query.inspectionCode) {
      // 使用检验单编号作为唯一查询条件
      this.queryParams.iqcCode = this.$route.query.inspectionCode;

      // 清空其他可能干扰查询的条件，确保查询精度
      Object.keys(this.queryParams).forEach(key => {
        if (key !== 'iqcCode' && key !== 'pageNum' && key !== 'pageSize') {
          this.queryParams[key] = null;
        }
      });

      this.$message.info('正在查找待检测单据，请稍候...');
    }
    this.getList();
  },
  methods: {
    /** 查询ldzl-qc列表 */
    getList() {
      this.loading = true;
      listIqc(this.queryParams).then(response => {
        // 确保返回的数据是数组
        this.iqcList = Array.isArray(response.rows) ? response.rows : [];
        this.total = response.total || 0;

        // 如果使用了检验单编号查询，尝试找到对应记录并高亮显示
        if (this.$route.query.inspectionCode) {
          // 安全检查 - 确保iqcList是数组且不为空
          if (this.iqcList && this.iqcList.length > 0) {
            const foundItem = this.iqcList.find(item => item && item.iqcCode === this.$route.query.inspectionCode);
            if (foundItem && foundItem.iqcId) {
              // 记录ID用于高亮显示
              this.highlightId = foundItem.iqcId;

              this.$message.success('找到待检测单据，已高亮显示');
              // 滚动到对应行（通过DOM操作，延迟确保表格已渲染）
              this.$nextTick(() => {
                try {
                  const rows = document.querySelectorAll('.el-table__row');
                  if (rows && rows.length > 0) {
                    // 安全遍历行
                    rows.forEach((row, index) => {
                      if (index < this.iqcList.length &&
                          this.iqcList[index] &&
                          this.iqcList[index].iqcId == this.highlightId) {
                        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                      }
                    });
                  }
                } catch (error) {
                  console.error('滚动到高亮行时出错:', error);
                }
              });
            } else {
              // 未找到时，给出明确的提示，并提供查询建议
              this.$message.warning({
                message: '未找到指定编号的检验单，请尝试调整查询条件',
                duration: 5000
              });

              // 自动重置查询，重新获取完整列表，便于用户手动查找
              this.$confirm('是否重置查询条件，显示所有检验单?', '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'info'
              }).then(() => {
                this.resetQuery();
              }).catch(() => {});
            }
          } else {
            this.$message.warning({
              message: '查询结果为空，未找到任何检验单',
              duration: 5000
            });
          }
        }
      }).catch(error => {
        console.error("获取列表失败:", error);
        this.$modal.msgError("数据加载失败");
        this.iqcList = []; // 确保发生错误时列表被重置为空数组
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 清除高亮ID，因为用户主动搜索了
      this.highlightId = null;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 清除高亮ID
      this.highlightId = null;
      this.handleQuery();
    },
    // 获取行样式
    getRowStyle(row) {
      const baseStyle = {height: '40px'};
      // 确保row和row.row存在且有效
      if (this.highlightId && row && row.row && row.row.iqcId == this.highlightId) {
        return {
          ...baseStyle,
          backgroundColor: '#fdf5e6', // 淡黄色背景
          fontWeight: 'bold',
          color: '#ff7800'
        };
      }
      return baseStyle;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.iqcId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 行点击事件，不再跳转到详情页面
    handleRowClick(row, column, event) {
      // 防止点击复选框时触发行点击事件
      if (column.type === 'selection') {
        return;
      }

      // 移除导航到详情页面的逻辑，因为现在只通过点击编码才导航
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {}
      this.open = true
      this.title = "添加ldzl-qc"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.form = {}
      const iqcId = row.iqcId || this.ids

      // 清除高亮状态，因为要进入修改模式
      this.highlightId = null;

      getIqc(iqcId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改ldzl-qc"
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {


      const rqc = row || {};
      const iqcIds = row.iqcId || this.ids;

      // 检查检测结果是否为待检
      if (rqc.checkResult !== 3 && rqc.checkResult !== '3') {
        this.$modal.msgError("只能删除检测结果为待检的单据");
        return;
      }
      
      this.$modal.confirm('确认删除?').then(() => {
        return delIqc(iqcIds).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(error => {
          this.$modal.msgError("删除失败");
        });
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ldzl-qc/iqc/export', {
        ...this.queryParams
      }, `iqc_${new Date().getTime()}.xlsx`)
    },
    // 对话框取消
    handleDialogCancel() {
      this.open = false
    },
    // 对话框成功
    handleDialogSuccess(sourceData) {
      this.open = false;
      // 刷新列表
      this.getList();
    },
    /** 缺陷记录按钮操作 */
    handleDefectRecord(row) {
      if (!row || !row.iqcId) {
        this.$modal.msgError("请选择有效的检测单");
        return;
      }

      // 设置ID和标题
      this.defectIqcId = row.iqcId;
      this.defectTitle = row.iqcCode || '';

      // 打开对话框
      this.defectOpen = true;
    },
    // 格式化检测结果
    formatCheckResult(value) {
      if (value === undefined || value === null) return '';
      const result = this.checkResultOptions.find(item => item.value === value);
      return result ? result.label : value;
    },
    // 格式化单据状态
    formatStatus(value) {
      if (value === undefined || value === null) return '';
      const result = this.statusOptions.find(item => item.value === value);
      return result ? result.label : value;
    },
    // 获取来源单据类型标签类型
    getSourceDocTypeTagType(value) {
      if (value === 1 || value === '1') return 'success';
      if (value === 2 || value === '2') return 'info';
      if (value === 3 || value === '3') return 'warning';
      if (value === 4 || value === '4') return 'danger';
      return '';
    },
    // 获取检测结果标签类型
    getCheckResultTagType(value) {
      if (value === '1' || value === 1) return 'success';
      if (value === '2' || value === 2) return 'danger';
      if (value === '3' || value === 3) return 'info';
      return '';
    },
    // 获取单据状态标签类型
    getStatusTagType(value) {
      if (value === '1' || value === 1) return 'info';
      if (value === '2' || value === 2) return 'success';
      if (value === '3' || value === 3) return 'warning';
      return '';
    },
    // 跳转到详情页的新方法
    goToDetail(row) {
      if (!row || !row.iqcId) return;

      console.log('准备跳转到详情页，ID:', row.iqcId);
      // 使用ID参数而不是编码
      this.$router.push(`/qc/IncomingInspection/detail/${row.iqcId}`);
    },
  }
}
</script>

<style scoped>
.clickable-code {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
  font-weight: bold;
}

.clickable-code:hover {
  color: #66b1ff;
}

.clickable-code:active {
  color: #3a8ee6;
}

/* 高亮待检行样式 */
.highlight-row {
  background-color: #fdf5e6 !important;
  font-weight: bold;
  color: #ff7800;
}

/* 优化固定列样式 */
::v-deep .el-table__fixed-right {
  height: 100% !important;
}

::v-deep .el-table__fixed-left {
  height: 100% !important;
}

::v-deep .el-table__row td {
  height: 40px !important;
}

/* 确保所有单元格内容垂直居中 */
::v-deep .el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

/* 调整按钮单元格内容样式 */
::v-deep .el-table .cell .el-button {
  padding: 3px 0;
  margin: 0 3px;
}
</style>
